<template>
  <div class="bill-container">
    <el-card>
      <div slot="header" class="header">
        <span>收支账单</span>
        <el-button type="primary" @click="handleAdd">新增账单</el-button>
      </div>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型">
            <el-option label="全部" value=""></el-option>
            <el-option label="收入" value="收入"></el-option>
            <el-option label="支出" value="支出"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="billList"
        style="width: 100%"
        v-loading="loading">
        <el-table-column
          prop="consumeDate"
          label="日期"
          width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.consumeDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="consumeType"
          label="类型"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === '收入' ? 'success' : 'danger'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="reason"
          label="分类"
          width="120">
        </el-table-column>
        <el-table-column
          prop="amount"
          label="金额"
          width="120">
          <template slot-scope="scope">
            <span :class="scope.row.type === '收入' ? 'income' : 'expense'">
              {{ scope.row.type === '收入' ? '+' : '-' }}¥{{ scope.row.amount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="theme"
          label="描述">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button
              @click="handleEdit(scope.row)"
              type="text"
              size="small">
              编辑
            </el-button>
            <el-button
              @click="handleDelete(scope.row)"
              type="text"
              size="small"
              class="delete-btn">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="billForm" :rules="rules" ref="billForm" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="billForm.type">
            <el-radio label="收入">收入</el-radio>
            <el-radio label="支出">支出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="billForm.category" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="billForm.amount" :precision="2" :step="0.1" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="billForm.date"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="billForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BillList',
  data() {
    return {
      searchForm: {
        type: '',
        category: '',
        dateRange: []
      },
      billList: [],
      loading: false,
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增账单',
      billForm: {
        type: '支出',
        category: '',
        amount: 0,
        date: '',
        description: ''
      },
      rules: {
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ]
      },
      categories: [
        { value: '餐饮', label: '餐饮' },
        { value: '交通', label: '交通' },
        { value: '购物', label: '购物' },
        { value: '娱乐', label: '娱乐' },
        { value: '工资', label: '工资' },
        { value: '奖金', label: '奖金' },
        { value: '其他', label: '其他' }
      ]
    }
  },
  created() {
    this.fetchBillList()
  },
  methods: {
    async fetchBillList() {
      this.loading = true
      try {
        let response
        const params = {
          pageNo: this.page.current,
          pageSize: this.page.size,
          orderBy: 'consume_date',
          orderType: 'desc'
        }

        // 添加查询条件
        if (this.searchForm.category) {
          params.reason = this.searchForm.category
        }
        if (this.searchForm.description) {
          params.theme = this.searchForm.description
        }
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.formatDateParam(this.searchForm.dateRange[0])
          params.endDate = this.formatDateParam(this.searchForm.dateRange[1])
        }

        // 根据类型分别查询
        if (this.searchForm.type === '收入') {
          response = await this.$http.get('/billin/list', { params })
          if (response.data.code === 20000) {
            this.billList = response.data.data.rows.map(item => ({
              ...item,
              type: '收入'
            }))
            this.page.total = response.data.data.total
          }
        } else if (this.searchForm.type === '支出') {
          response = await this.$http.get('/billout/list', { params })
          if (response.data.code === 20000) {
            this.billList = response.data.data.rows.map(item => ({
              ...item,
              type: '支出'
            }))
            this.page.total = response.data.data.total
          }
        } else {
          // 查询所有
          const [inResponse, outResponse] = await Promise.all([
            this.$http.get('/billin/list', { params }),
            this.$http.get('/billout/list', { params })
          ])
          
          const inData = (inResponse.data.data.rows || []).map(item => ({
            ...item,
            type: '收入'
          }))
          const outData = (outResponse.data.data.rows || []).map(item => ({
            ...item,
            type: '支出'
          }))
          
          // 合并并按日期排序
          this.billList = [...inData, ...outData].sort((a, b) => 
            new Date(b.consumeDate) - new Date(a.consumeDate)
          )
          this.page.total = (inResponse.data.data.total || 0) + (outResponse.data.data.total || 0)
        }
      } catch (error) {
        console.error('获取账单列表失败:', error)
        this.$message.error('获取账单列表失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.page.current = 1
      this.fetchBillList()
    },
    resetSearch() {
      this.searchForm = {
        type: '',
        category: '',
        dateRange: []
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.page.size = val
      this.fetchBillList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.fetchBillList()
    },
    handleAdd() {
      this.dialogTitle = '新增账单'
      this.billForm = {
        type: '支出',
        category: '',
        amount: 0,
        date: '',
        description: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑账单'
      this.billForm = {
        id: row.id,
        type: row.type,
        category: row.reason,
        amount: row.amount,
        date: new Date(row.consumeDate),
        description: row.theme
      }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该账单记录吗？', '提示', {
          type: 'warning'
        })
        
        if (row.type === '收入') {
          await this.$http.delete(`/billin/${row.id}`)
        } else {
          await this.$http.delete(`/billout/${row.id}`)
        }
        
        this.$message.success('删除成功')
        this.fetchBillList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Delete bill error:', error)
          this.$message.error('删除失败')
        }
      }
    },
    submitForm() {
      this.$refs.billForm.validate(async valid => {
        if (valid) {
          try {
            const date = new Date(this.billForm.date)
            date.setHours(23, 59, 59) // 设置为当天的最后一秒
            
            const billData = {
              theme: this.billForm.description,
              amount: this.billForm.amount,
              consumeDate: date.toISOString(),
              reason: this.billForm.category,
              consumeType: this.billForm.type
            }

            if (this.billForm.type === '收入') {
              if (this.billForm.id) {
                await this.$http.put(`/billin/${this.billForm.id}`, billData)
              } else {
                await this.$http.post('/billin', billData)
              }
            } else {
              if (this.billForm.id) {
                await this.$http.put(`/billout/${this.billForm.id}`, billData)
              } else {
                await this.$http.post('/billout', billData)
              }
            }

            this.$message.success('保存成功')
            this.dialogVisible = false
            this.fetchBillList()
          } catch (error) {
            console.error('Save bill error:', error)
            this.$message.error('保存失败')
          }
        }
      })
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    formatDateParam(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.bill-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.income {
  color: #67C23A;
}

.expense {
  color: #F56C6C;
}

.delete-btn {
  color: #F56C6C;
}
</style> 